package com.study.userserviceprovider.util;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Map;

/**
 * @description：jwt操作
 * @author：李军荣
 * @date: 2020/12/28 11:48
 */
@Slf4j
public class JwtUtil {

    private static String SECRET_KEY = "custom";

    private static Key getKeyInstance(){
        SignatureAlgorithm  signatureAlgorithm = SignatureAlgorithm.HS256;
        byte[] keySecretByte =  DatatypeConverter.parseBase64Binary(SECRET_KEY);
        Key key = new SecretKeySpec(keySecretByte,signatureAlgorithm.getJcaName());
        return key;
    }

    /**
     * @Title: generatorToken
     * @Description: 生成token
     * @Date 2020/12/28 13:58
     * @author 李军荣
     * @Param: payLoad
     * @return java.lang.String
     */
    public static String generatorToken(Map<String,Object> payLoad){
        ObjectMapper objectMapper = new ObjectMapper();
        String token = null;
        try {
            token = Jwts.builder().setPayload(objectMapper.writeValueAsString(payLoad))
                    .signWith(SignatureAlgorithm.HS256,getKeyInstance()).compact();
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            log.info("jwt generator exception:"+e);
        }
        return token;
    }


    /**
     * @Title: parseToken
     * @Description: 根据token解析出token中的内容
     * @Date 2020/12/28 14:01
     * @author 李军荣
     * @Param: token
     * @return io.jsonwebtoken.Claims
     */
    public static Claims parseToken(String token){
        Jws<Claims> clamisJws = Jwts.parser().setSigningKey(getKeyInstance()).parseClaimsJws(token);
        return clamisJws.getBody();
    }

}
